<template>
  <div class="list-item" @click="viewDetail">
    <div>{{ title }}</div>
    <div v-if="approval_count > 0" class="subscript">{{ approval_count }}</div>
    <div class="list-total">{{ numberser }}</div>
    <div class="list-dec">详情&nbsp;&gt;</div>
  </div>

  <a-drawer
    :title="'收支提醒详情'"
    v-model:visible="visible"
    :destroyOnClose="true"
    :width="1000"
  >
    <a-tabs
      v-model:activeKey="drawerTabActive"
      :animated="true"
      ref="tabsRef"
      @change="handleTabChange"
    >
      <a-tab-pane
        :key="index + 1"
        :tab="item.title"
        v-for="(item, index) in list"
      >
        <a-table
          :columns="item.columns"
          :dataSource="dataSource"
          :loading="tableLoading"
          :pagination="pagination"
          @change="handleTableChange"
          rowKey="id"
          :scroll="{ x: 'max-content' }"
          class="mt-10"
          :customRow="customRow"
        >
          <template #bodyCell="{ text, record, index, column }">
            <template v-if="column.key === 'owner_name'">
              <span
                :class="record.owner_id ? 'link' : ''"
                @click.stop="onOwnerClick(record.owner_id)"
                >{{ text || "--" }}</span
              >
            </template>
          </template>
        </a-table>
      </a-tab-pane>
    </a-tabs>
  </a-drawer>

  <!-- 账单详情 -->
  <BillDetailDrawer
    :visible="billDetailVisible"
    :id="billDetailId"
    @cancel="billDetailVisible = false"
  />

  <!-- 租客详情 -->
  <OwnerDetailDrawer
    :visible="ownerDetailVisible"
    :id="ownerId"
    @cancel="ownerDetailVisible = false"
  />
</template>

<script>
import {
  defineComponent,
  ref,
  computed,
  watch,
  nextTick,
  reactive,
  toRefs,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import {
  PlusOutlined,
  ExclamationCircleOutlined,
  SearchOutlined,
} from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import { message, Modal } from "ant-design-vue";
import utils from "@/common/utils/utils";
import store from "@/store";
import BillDetailDrawer from "@/views/bill/BillDetail/modules/BillDetailDrawer.vue";
import OwnerDetailDrawer from "@/views/village/OwnerManage/modules/OwnerDetailDrawer.vue";
import RouteUtils from "../../../router/router.utils.js";
export default defineComponent({
  name: "TotalThreeSpan",
  props: {
    title: {
      type: String,
      default: "",
    },
    index: {
      type: [String, Number],
      default: 0,
    },
  },
  components: {
    OwnerDetailDrawer,
    BillDetailDrawer,
  },
  setup(props, context) {
    const state = reactive({
      numberser: 0,
      approval_count: 0,
      visible: false,
      drawerTabActive: 1,
      list: [],
      dataSource: [],
      tableLoading: false,
      billDetailVisible: false,
      billDetailId: 0,
      ownerId: 0,
      ownerDetailVisible: false,
      listTimer: null,
    });

    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));

    const getDetail = (active) => {
      state.drawerTabActive = active;
      state.visible = true;
      reset();
      getTableData();
    };

    const handleTabChange = () => {
      reset();
      getTableData();
    };

    const reset = () => {
      page.value = 1;
      total.value = 0;
      state.dataSource = [];
    };

    const getTableData = () => {
      clearTimeout(state.listTimer);
      state.listTimer = setTimeout(() => {
        state.tableLoading = true;
        let TabActive = 0;
        if (state.drawerTabActive == 1) {
          TabActive = 1;
        } else if (state.drawerTabActive == 2) {
          TabActive = 3;
        }
        let params = {
          page: page.value,
          limit: limit.value,
          tab: TabActive,
        };
        request
          .get("/org", "/workbench/overdueBillList", params)
          .then((res) => {
            state.dataSource = res.list;
            total.value = res.total;
            state.tableLoading = false;
          })
          .catch((err) => {
            state.tableLoading = false;
          });
      }, 500);
    };

    const handleTableChange = (pager, filters, sorter) => {
      page.value = pager.current;
      limit.value = pager.pageSize;
      getTableData();
    };

    const getBossData = () => {
      let data = [];
      data = [
        {
          title: "目前已到期应收",
          columns: RECEIVABLE_COLUMNS,
        },
        {
          title: "未来7天应收",
          columns: RECEIVABLE_COLUMNS,
        },
      ];
      state.list = data;
      state.spinning = true;
      request
        .get("/org", "/workbench/billStatistics")
        .then((res) => {
          data[0].total = res[`total1`];
          data[1].total = res[`total3`];
          state.list = data;
          state.spinning = false;
        })
        .catch((err) => {
          state.spinning = false;
        });
    };

    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: (e) => handleTableRowClick(record),
      };
    };

    const handleTableRowClick = (record) => {
      // 账单详情
      state.billDetailId = record.id;
      state.billDetailVisible = true;
    };

    const onOwnerClick = (id) => {
      if (id) {
        state.ownerId = id;
        state.ownerDetailVisible = true;
      }
    };

    const viewDetail = () => {
      let href = window.location.href;
      let ref = href.substr(0, href.indexOf("#"));

      if (props.title == "房间总数") {
        window.microApp.forceDispatch({
          type: "SetMicroPages",
          microInfo: {
            microId: `org_houseResourcest`,
            app: 'org',
            name: `房间列表`,
            url: `/village/houseResources`,
          }
        })
      }
      if (props.title == "住户总数") {
        window.microApp.forceDispatch({
          type: "SetMicroPages",
          microInfo: {
            microId: `org_ownerList`,
            app: 'org',
            name: `住户列表`,
            url: `village/ownerList`,
          }
        })
      }
      if (props.title == "车辆总数") {
        window.microApp.forceDispatch({
          type: "SetMicroPages",
          microInfo: {
            microId: `workPark_carList`,
            app: 'workPark',
            name: `车辆列表`,
            url: `/carManage/list`,
            sideAlias: 'workPark',
          }
        })
      }
      if (props.title == "车位总数") {
        window.microApp.forceDispatch({
          type: "SetMicroPages",
          microInfo: {
            microId: `workPark_spaceList`,
            app: 'workPark',
            name: `车位管理`,
            url: `/parkManage/spaceList`,
            sideAlias: 'workPark',
          }
        })
      }
      if (props.title == "今日已处理工单数") {
        window.microApp.forceDispatch({
          type: "SetMicroPages",
          microInfo: {
            microId: `workOrder_manage`,
            app: 'workOrder',
            name: `工单列表`,
            url: `/repair/control`,
          }
        })
      }
      if (props.title == "今日访客数") {
        window.microApp.forceDispatch({
          type: "SetMicroPages",
          microInfo: {
            microId: `workVisitor_visitorList`,
            app: 'workVisitor',
            name: `访客列表`,
            url: `/basic/visitorList`,
          }
        })
      }
      if (props.title == "未来7天应收（元）") {
        getDetail(2);
      }
      if (props.title == "目前已到期应收（元）") {
        getDetail(1);
      }
    };

    const info = () => {
      if (props.title == "房间总数") {
        request.get("/village", `/workbench/room_count`).then((res) => {
          state.numberser = res.count;
        });
      }
      if (props.title == "住户总数") {
        request.get("/village", `/workbench/user_count`).then((res) => {
          state.numberser = res.count.user_count;
          state.approval_count = res.count.approval_count;
        });
      }
      if (props.title == "车辆总数") {
        request.get("/work_park", `/workbench/car_count`).then((res) => {
          state.numberser = res.total;
        });
      }
      if (props.title == "车位总数") {
        request.get("/work_park", `/workbench/park_space_count`).then((res) => {
          state.numberser = res.total;
        });
      }
      if (props.title == "今日已处理工单数") {
        request.get("/org", `/workbench/workorder_done_count`).then((res) => {
          state.numberser = res.total;
        });
      }
      if (props.title == "今日访客数") {
        request.get("/work_visitor", `/workbench/visitor_count`).then((res) => {
          state.numberser = res.total;
        });
      }
      if (props.title == "未来7天应收（元）") {
        request
          .get("/org", `/workbench/billStatistics`, { card: "card_3" })
          .then((res) => {
            state.numberser = res.total3;
            getBossData();
          });
      }
      if (props.title == "目前已到期应收（元）") {
        request
          .get("/org", `/workbench/billStatistics`, { card: "card_1" })
          .then((res) => {
            state.numberser = res.total1;
            getBossData();
          });
      }
    };

    info();

    return {
      ...toRefs(state),
      viewDetail,
      getDetail,
      handleTabChange,
      getTableData,
      reset,
      getBossData,
      pagination,
      handleTableChange,
      customRow,
      handleTableRowClick,
      onOwnerClick,
    };
  },
});

const RECEIVABLE_COLUMNS = [
  {
    title: "对方名称",
    dataIndex: "owner_name",
    key: "owner_name",
    fixed: "left",
    className: "owner_name",
    width: 120,
  },
  {
    title: "楼宇名称",
    key: "build_name",
    dataIndex: "build_name",
    fixed: store.getters.isMobile ? undefined : "left",
    width: 100,
  },
  {
    title: "费用类型",
    key: "cost_type_txt",
    dataIndex: "cost_type_txt",
    width: 105,
  },
  {
    title: "账单金额",
    dataIndex: "bill_amount",
    key: "bill_amount",
    width: 120,
    customRender: ({ text, record, index }) => {
      return "￥" + text || 0;
    },
  },
  {
    title: "应收金额",
    key: "receivable_payment",
    dataIndex: "receivable_payment",
    width: 120,
    customRender: ({ text, record, index }) => {
      return "￥" + text || 0;
    },
  },
  {
    title: "应收日期",
    dataIndex: "receivable_payment_date",
    key: "receivable_payment_date",
    width: 120,
  },
  {
    title: "有效期",
    dataIndex: "start_date",
    key: "start_date",
    width: 120,
    customRender: ({ text, record, index }) => {
      return record?.start_date + " ~ " + record?.end_date;
    },
  },
  {
    title: "滞纳金",
    dataIndex: "latefee_amount",
    key: "latefee_amount",
    width: 120,
    customRender: ({ text, record, index }) => {
      return "￥" + text || 0;
    },
  },
];
</script>

<style lang="less" scoped>
.list-item {
  height: 100%;
  width: 100%;
  background-color: #fff;
  border-radius: 8px;
  cursor: pointer;
  padding: 30px 18px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: relative;
  .list-dec {
    color: @primary-color;
  }

  .list-total {
    font-size: 22px;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    word-break: break-all;
  }

  &:hover {
    background-color: @primary-color;
    color: #fff;
    .list-dec {
      color: #fff;
    }
  }

  .subscript {
    position: absolute;
    top: 25px;
    left: 75px;
    display: inline-block;
    min-width: 20px;
    height: 20px;
    line-height: 20px;
    background-color: red;
    border-radius: 10px;
    color: white;
    padding-left: 6px;
    padding-right: 6px;
  }
}
</style>
